﻿using AutoServices.Common;
using AutoServices.Models;
using CommonUtil;
using Infrastructure.kflwyg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoServices.JobTask
{
    public class NameObj
    {
        public string UserID { get; set; }
        public string Names { get; set; }
    }
    public class UpLoadWorkerAndAttendanceTask : BaseJob<UpLoadWorkerAndAttendanceTask>
    {
        private kflwygHelper kflwygHelper = null;
        public UpLoadWorkerAndAttendanceTask()
        {
            kflwygHelper = new kflwygHelper();
        }
        public override void ExecuteProgramJob(SourceTaskItem sourceTask, LogTaskItem logTask)
        {
            _log.InfoFormat(DateTime.Now + Environment.NewLine + "UpLoadWorkerAndAttendanceTask 开始执行");
            Excate(sourceTask);
        }


        /// <summary>
        /// 
        /// </summary>
        private void Excate(SourceTaskItem sourceTask)
        {
            try
            {
                //同步工人信息
                string sqlStr = @"
                    SELECT B.Names, A.UserID
                    FROM dbo.t_Worker AS A
                        INNER JOIN dbo.Users AS B ON A.UserID = B.UserID
                    WHERE A.IsAsync = '0'
                ";
                _log.InfoFormat(DateTime.Now + Environment.NewLine + "UpLoadWorkerAndAttendanceTask sqlStr:{0}", sqlStr);
                List<NameObj> workerList = new SQLHelper(sourceTask.ConnectionString).ExecuteQuery(sqlStr, CommandType.Text).ToList<NameObj>();
                StringBuilder sbWorkerIDs = new StringBuilder("");
                for (int i = 0; i < workerList.Count; i++)
                {
                    string resultStr = kflwygHelper.AddProjectWorker(new AddProjectWorkerParam()
                    {
                        project_code = "475000200806003208",
                        corp_code = "91410300171072017D",
                        corp_name = "河南国安建设集团有限公司",
                        team_name = "国安建设一队",
                        worker_name = workerList[i].Names,
                    });
                    sbWorkerIDs.AppendFormat("'{0}'", workerList[i].UserID);
                    if (i < workerList.Count - 1)
                    {
                        sbWorkerIDs.Append(",");
                    }

                }
                int result = 0;
                //标记更新过的数据
                if (!string.IsNullOrEmpty(sbWorkerIDs.ToString()))
                {
                    sqlStr = string.Format(@"
                        UPDATE t_Worker
                        SET IsAsync = '1'
                        WHERE UserID IN( {0} )
                        ", sbWorkerIDs.ToString());
                    result = new SQLHelper(sourceTask.ConnectionString).ExecuteNonQuery(sqlStr, CommandType.Text);
                }

                sbWorkerIDs.Clear();

                //删除被标记为删除的工人
                sqlStr = @"
                    SELECT A.UserID AS Names, B.ICNum AS UserID
                    FROM dbo.t_Worker AS A
                        INNER JOIN dbo.Users AS B ON A.UserID = B.UserID
                    WHERE A.IsDelete = '1'
                ";
                _log.InfoFormat(DateTime.Now + Environment.NewLine + "UpLoadWorkerAndAttendanceTask sqlStr:{0}", sqlStr);
                workerList = new SQLHelper(sourceTask.ConnectionString).ExecuteQuery(sqlStr, CommandType.Text).ToList<NameObj>();

                sbWorkerIDs = new StringBuilder("");
                for (int i = 0; i < workerList.Count; i++)
                {
                    string resultStr = kflwygHelper.DeleteProjectWorker("475000200806003208", "91410300171072017D", "国安建设一队", workerList[i].UserID);
                    sbWorkerIDs.AppendFormat("'{0}'", workerList[i].Names);
                    if (i < workerList.Count - 1)
                    {
                        sbWorkerIDs.Append(",");
                    }
                }
                //标记更新过的数据
                if (!string.IsNullOrEmpty(sbWorkerIDs.ToString()))
                {
                    sqlStr = string.Format("UPDATE t_Worker SET IsDelete='2' WHERE UserID IN ({0})", sbWorkerIDs.ToString());
                    result = new SQLHelper(sourceTask.ConnectionString).ExecuteNonQuery(sqlStr, CommandType.Text);
                }

                sbWorkerIDs.Clear();

                //同步工人考勤数据
                sqlStr = @"
                    SELECT RecordID, project_code, corp_code, corp_name, team_name, corp_type, UserID, Names, idcard_number, idcard_type,
                           direction, attend_type, lng, lat, channel, date, IsAsync
                    FROM t_Record
                    WHERE IsAsync = '0'
                ";
                _log.InfoFormat(DateTime.Now + Environment.NewLine + "UpLoadWorkerAndAttendanceTask sqlStr:{0}", sqlStr);

                List<AddWorkerAttendanceParamSql> attendanceList = new SQLHelper(sourceTask.ConnectionString).ExecuteQuery(sqlStr, CommandType.Text).ToList<AddWorkerAttendanceParamSql>();

                //工人考勤数据上传
                for (int i = 0; i < attendanceList.Count; i++)
                {
                    //string result = new HttpMethod().SendAttendanceInfo(info, _log, sourceTask.ConnectionString);
                    var info = attendanceList[i];
                    string resultStr = kflwygHelper.AddWorkerAttendance(new AddWorkerAttendanceParam()
                    {
                        project_code = info.project_code,
                        corp_code = info.corp_code,
                        corp_name = info.corp_name,
                        team_name = info.team_name,
                        idcard_type = info.idcard_type,
                        idcard_number = info.idcard_number,
                        date = info.date,
                        direction = info.direction,
                        channel = info.channel,
                        attend_type = info.attend_type,
                        lng = info.lng,
                        lat = info.lat,
                    });
                    sbWorkerIDs.AppendFormat("'{0}'", attendanceList[i].RecordID);
                    if (i < attendanceList.Count - 1)
                    {
                        sbWorkerIDs.Append(",");
                    }
                }
                if (!string.IsNullOrEmpty(sbWorkerIDs.ToString()))
                {
                    sqlStr = string.Format("UPDATE t_Record SET IsAsync='1' WHERE RecordID IN ({0})", sbWorkerIDs.ToString());
                    int result1 = new SQLHelper(sourceTask.ConnectionString).ExecuteNonQuery(sqlStr, CommandType.Text);
                    _log.InfoFormat("UpLoadWorkerAndAttendanceTask result:{0}", result);

                }

            }
            catch (Exception ex)
            {
                _log.InfoFormat(DateTime.Now + Environment.NewLine + "UpLoadWorkerAndAttendanceTask 发生异常:{0}", ex.Message);
            }
        }
    }
}
